package com.framework.cat.filter;

import com.alibaba.fastjson.JSON;
import com.dianping.cat.Cat;
import com.dianping.cat.message.Transaction;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author dongsufeng
 * @date 2021/11/23 10:22
 * @version 1.0
 */
public class LogServer {

	private static Logger log = LoggerFactory.getLogger(LogServer.class);


	public static Result log(Invoker<?> invoker, Invocation invocation ,String transactionType){
		String providerIp = RpcContext.getServiceContext().getLocalAddressString();
		String methodName = invocation.getMethodName();
		Transaction t = Cat.newTransaction(transactionType, methodName);
		try {
			log.info("RPC_CON_REQ {} PRO_HOST {} REQ {}", methodName, providerIp, JSON.toJSONString(invocation.getArguments()));
			Result result = invoker.invoke(invocation);
			if (result != null){
				Object value = result.getValue();
				log.info("RPC_CON_RSP {} PRO_HOST {} RSP {}",methodName,providerIp,JSON.toJSONString(value));
				t.setStatus(Transaction.SUCCESS);
				return result;
			}else {
				log.error("RPC_CON_RSP {} PRO_HOST {} RSP dubbo result is null",methodName,providerIp);
				throw new RpcException("dubbo result is null");
			}
		} catch (RpcException e) {
			log.error("RPC_CON_EX= {} PRO_HOST {}", methodName, providerIp, e);
			Cat.logError(e);
			t.setStatus(e);
			throw new RpcException(e);
		} finally {
			t.complete();
		}
	}
}
